package com.edu.aspect;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * ProductController 的横切类
 *
 *  用于打印相关的日志信息
 *
 */
@Slf4j
@Aspect
@Component
public class HttpAspect {

    /**
     * execution 说明
     * public 所有公用的方法
     * * 任意返回值
     * com.edu.controller.ProductController 类的全路径名
     * * 所有方法
     * (..) 任意参数
     *
     */
    @Pointcut("execution(public * com.edu.controller.ProductController.*(..))")
    public void log(){}

    /**
     * 日志相关
     * url 请求路径
     * method 请求类型
     * ip 请求方ip地址
     * classMethod 请求的类方法
     * args 请求的参数
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        log.info("请求路径 url={}", request.getRequestURL());
        log.info("请求类型 method={}", request.getMethod());
        log.info("请求方地址 address={}", request.getRemoteAddr());
        log.info("请求类方法 classMethod={}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("请求参数 args={}", joinPoint.getArgs());

    }

    @After("log()")
    public void doAfter(){
        log.info("doAfter");
    }

    @AfterReturning(returning = "o", pointcut = "log()")
    public void doAfterReturning(Object o){
            log.info("response={}",o);
    }

}
